/********************************************************************************
 * SearchAction.java
 *
 * Created by Jigar Mistry
 * Last modified Date: Jan 22, 2009 3:26:50 PM by Jigar Mistry
 * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ********************************************************************************/
package com.printeverywhere.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionContext;
import com.printeverywhere.delegator.CategoryManagerServiceDelegator;
import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.delegator.LocationCategoriesServiceDelegator;
import com.printeverywhere.dto.BrowseItems;
import com.printeverywhere.dto.GeneralCategoriesWOS;
import com.printeverywhere.dto.Itemtype;
import com.printeverywhere.dto.ListingOptions;
import com.printeverywhere.dto.UserFavoritesSearch;
import com.printeverywhere.util.AdminConstants;
import com.printeverywhere.util.CommonUtil;
import com.printeverywhere.util.DateUtil;
import com.printeverywhere.util.SessionUtil;


public class SearchAction extends FrontBaseSupport implements ServletRequestAware {

	private static final long serialVersionUID = 1L;

	private HttpServletRequest request;

	private String sortBy;

	private String titleValue;

	private Integer searchIn;

	private Integer ItemType;

	private Integer categories;

	private Integer locations;

	private String languages;

	private String city;

	private Itemtype type;

	private Integer quantity;

	private Integer bidderId;

	private Integer sellerId;

	private Integer itemId;

	private Integer buyFrom;

	private Integer buyTo;

	private Integer priceFrom;

	private Integer priceTo;

	private Date endTime;

	private Integer pageSize;

	private String[] categoriesList;

	private boolean titleAndDescription;

	private List<BrowseItems> itemList = new ArrayList<BrowseItems>();

	public SearchAction() {
		super(false, false);
		setCategoryDisplay(true);
	}

	public String execute() {
		if(pageSize == null)
			pageSize = 25;

		ListingOptions listingOptions = (ListingOptions) ActionContext.getContext().getApplication().get(AdminConstants.LISTING_OPTIONS);
		StringBuffer sql = new StringBuffer();

		if(request.getParameter("cid") != null && request.getParameter("type") != null) {
			GeneralCategoriesWOS cat = CategoryManagerServiceDelegator.getWOS(Integer.parseInt(request.getParameter("cid")));
			DynamicTreeSelectAction dynamicTreeSelectAction = new DynamicTreeSelectAction();
			categoriesList = dynamicTreeSelectAction.getGeneralCategoriesFromCategoryId(cat.getCategoryId());

			String locConition = "";
			if(locations != 0) {
				locConition = " AND (region IN (" + CommonUtil.getLocationChildrensHierarchy(LocationCategoriesServiceDelegator.getWOS(locations))  + ") OR country IN (" + CommonUtil.getLocationChildrensHierarchy(LocationCategoriesServiceDelegator.getWOS(locations))  + ") OR state IN (" + CommonUtil.getLocationChildrensHierarchy(LocationCategoriesServiceDelegator.getWOS(locations))  + "))";
			}

			String cityConition = "";
			if(city != null) {
				cityConition = " and city like '%" + city + "%'";
			}

			if(request.getParameter("cid").equals("0"))
				sql.append("SELECT i.itemId, title, quantity, shipPayment, startBid, endTime FROM items i, item_categories ig, general_categories g, location_categories l where (i.region = l.categoryid OR i.country = l.categoryid OR i.state = l.categoryid) AND i.itemid = ig.itemid AND ig.categoryid = g.categoryid AND i.type = ").append(request.getParameter("type")).append(locConition).append(cityConition).append(";");
			else
				sql.append("SELECT i.itemId, title, quantity, shipPayment, startBid, endTime FROM items i, item_categories ig, general_categories g, location_categories l where (i.region = l.categoryid OR i.country = l.categoryid OR i.state = l.categoryid) AND i.itemid = ig.itemid AND ig.categoryid = g.categoryid and g.categoryId IN (" + CommonUtil.getChildrensHierarchy(cat) + ")").append(" AND i.type = ").append(request.getParameter("type")).append(locConition).append(cityConition).append(";");
		} else if(request.getParameter("cid") != null) {
			GeneralCategoriesWOS cat = CategoryManagerServiceDelegator.getWOS(Integer.parseInt(request.getParameter("cid")));
			DynamicTreeSelectAction dynamicTreeSelectAction = new DynamicTreeSelectAction();
			categoriesList = dynamicTreeSelectAction.getGeneralCategoriesFromCategoryId(cat.getCategoryId());

			String condition = "";

			if(request.getParameter("endsoon") != null) {
				condition = " AND endTime >= '" + DateUtil.addDate(DateUtil.getTodaysDate(), Calendar.HOUR, listingOptions.getGoingItemsMinutes() * -1) + "'";
				sortBy = "endsoon";
			} else if(request.getParameter("newlist") != null) {
				condition = " AND startTime <= '" + DateUtil.addDate(DateUtil.getTodaysDate(), Calendar.DATE, listingOptions.getNumberOfDaysForNewListings() * -1) + "'";
				sortBy = "newlist";
			} else if(request.getParameter("endtoday") != null) {
				condition = " AND endTime = '" + DateUtil.getTodaysDate() + "'";
				sortBy = "endtoday";
			}else if(request.getParameter("newtoday") != null) {
				condition = " AND startTime = '" + DateUtil.getTodaysDate() + "'";
				sortBy = "newtoday";
			}

			sql.append("SELECT i.itemId, title, quantity, shipPayment, startBid, endTime FROM items i, item_categories ig, general_categories g where i.itemid = ig.itemid AND ig.categoryid = g.categoryid and g.categoryId IN (" + CommonUtil.getChildrensHierarchy(cat) + ")").append(condition).append(";");
		} else if(request.getParameter("uid") != null && request.getParameter("type") != null) {
			sql.append("SELECT itemId, title, quantity, shipPayment, startBid, endTime FROM items WHERE userId = ").append(request.getParameter("uid")).append(" AND type = ").append(request.getParameter("type")).append(";");
		} else if(request.getParameter("uid") != null) {
			sql.append("SELECT itemId, title, quantity, shipPayment, startBid, endTime FROM items WHERE userId = ").append(request.getParameter("uid")).append(";");
		} else {
			type = (Itemtype) CommonFunctionDelegator.getObjectById("id", ItemType, Itemtype.class);

			DynamicTreeSelectAction dynamicTreeSelectAction = new DynamicTreeSelectAction();
			//categoriesList = dynamicTreeSelectAction.getGeneralCategoriesFromCategoryId(categories);

			boolean flag = false;
			String titleCondition = "";

			if(titleValue != null && !titleValue.trim().equals("")) {
				if(this.searchIn == 1)
					titleCondition = "title like '%" + titleValue + "%'";
				else
					titleCondition = "(description like '%" + titleValue + "%' OR title like '%" + titleValue + "%')";
				flag = true;
			}

			String typeCondition = "";
			if(ItemType != 0) {
				typeCondition = ((flag) ? " AND " : "")  + "type = " + ItemType;
				flag = true;
			}

			String langCondition = "";
			if(!languages.equals("0")) {
				langCondition = ((flag) ? " AND " : "")  + "itemLanguage like '" + languages + "'";
				flag = true;
			}

			String catCondition = "";
			if(categories != 0) {
				catCondition = ((flag) ? " AND " : "")  + "g.categoryId IN (" + CommonUtil.getChildrensHierarchy(CategoryManagerServiceDelegator.getWOS(categories))  + ")";
				flag = true;
			}

			String locConition = "";
			if(locations != 0) {
				locConition = ((flag) ? " AND " : "")  + "(region IN (" + CommonUtil.getLocationChildrensHierarchy(LocationCategoriesServiceDelegator.getWOS(locations))  + ") OR country IN (" + CommonUtil.getLocationChildrensHierarchy(LocationCategoriesServiceDelegator.getWOS(locations))  + ") OR state IN (" + CommonUtil.getLocationChildrensHierarchy(LocationCategoriesServiceDelegator.getWOS(locations))  + "))";
				flag = true;
			}

			sql.append("SELECT i.itemId, title, quantity, shipPayment, startBid, endTime FROM items i, item_categories ig, general_categories g");
			if(flag) {
				sql.append(" WHERE ").append(titleCondition).append(typeCondition).append(langCondition).append(catCondition).append(locConition).append(";");
			} else {
				sql.append(";");
			}

		}

		System.out.println(sql.toString());
		populateBrowseItems(sql.toString());

		return SUCCESS;
	}

	public String findBySmartSearch() {
		if(pageSize == null)
			pageSize = 25;

		if(request.getParameter("id") != null && request.getParameter("sort") != null) {
			UserFavoritesSearch userFavoritesSearch = (UserFavoritesSearch) CommonFunctionDelegator.getObjectById("id", Integer.parseInt(request.getParameter("id")), UserFavoritesSearch.class);
			if(userFavoritesSearch.getUser().getId() == SessionUtil.getUser(request).getId()) {
				ItemType = userFavoritesSearch.getType().getId();
				languages = userFavoritesSearch.getLanguage();
				categories = userFavoritesSearch.getCategoryId().getCategoryId();
				locations = userFavoritesSearch.getRegionId().getCategoryId();
				priceFrom = userFavoritesSearch.getPriceFrom();
				priceTo = userFavoritesSearch.getPriceTo();
				buyFrom = userFavoritesSearch.getBuyFrom();
				buyTo = userFavoritesSearch.getBuyTo();
				itemId = userFavoritesSearch.getItems().getItemId();
				endTime = userFavoritesSearch.getDate();
				sortBy = request.getParameter("sort");
			}
		}
		if (this.titleValue != null && !this.titleValue.trim().equals("")) {
			ListingOptions listingOptions = (ListingOptions) ActionContext.getContext().getApplication().get(AdminConstants.LISTING_OPTIONS);

			type = (Itemtype) CommonFunctionDelegator.getObjectById("id", ItemType, Itemtype.class);

			//DynamicTreeSelectAction dynamicTreeSelectAction = new DynamicTreeSelectAction();
			//categoriesList = dynamicTreeSelectAction.getGeneralCategoriesFromCategoryId(categories);

			String titleCondition = " title like '" + titleValue.toString() + "'";

			if(this.titleAndDescription)
				titleCondition = "(description like '%" + titleValue + "%' OR title like '%" + titleValue + "%')";

			String typeCondition = "";
			if(ItemType != 0) {
				typeCondition = " AND type = " + ItemType;
			}

			String langCondition = "";
			if(!languages.equals("0")) {
				langCondition = " AND itemLanguage like '" + languages + "'";
			}

			String catCondition = "";
			if(categories != 0) {
				catCondition = " AND categoryId IN (SELECT categoryId FROM general_categories WHERE mainparentId = (SELECT mainparentId FROM general_categories WHERE categoryId = " + categories + ") AND categoryId >= " + categories + ")";
			}

			String locConition = "";
			if(locations != 0) {
				locConition = " AND (region IN (SELECT categoryId FROM location_categories WHERE mainparentId = (SELECT mainparentId FROM location_categories WHERE categoryId = " + locations + ") AND categoryId >= " + locations + ") OR country IN (SELECT categoryId FROM location_categories WHERE mainparentId = (SELECT mainparentId FROM location_categories WHERE categoryId = " + locations + ") AND categoryId >= " + locations + ") OR state IN(SELECT categoryId FROM location_categories WHERE mainparentId = (SELECT mainparentId FROM location_categories WHERE categoryId = " + locations + ") AND categoryId >= " + locations + "))";
			}

			String priceFromConition = "";
			if (priceFrom != null) {
				priceFromConition = " AND startBid >= " + priceFrom;
			}

			String priceToConition = "";
			if (priceTo != null) {
				priceToConition = " AND startBid <= " + priceTo;
			}

			String buyFromConition = "";
			if (buyFrom != null) {
				buyFromConition = " AND startBid >= " + buyFrom;
			}

			String buyToConition = "";
			if (buyTo != null) {
				buyToConition = " AND startBid <= " + buyTo;
			}

			String itemConition = "";
			if (itemId != null) {
				itemConition = " AND itemId = " + itemId;
			}

			String timeConition = "";
			if (endTime != null) {
				timeConition = " AND endTime <= '" + DateUtil.getTodaysDate() + "'";
			}

			String endSoonConition = "";
			if(sortBy != null && sortBy.equalsIgnoreCase("endsoon")) {
				endSoonConition = " AND endTime >= '" + DateUtil.addDate(DateUtil.getTodaysDate(), Calendar.HOUR, listingOptions.getGoingItemsMinutes() * -1) + "'";
			}

			String newListConition = "";
			if(sortBy != null && sortBy.equalsIgnoreCase("newlist")) {
				newListConition = " AND startTime <= '" + DateUtil.addDate(DateUtil.getTodaysDate(), Calendar.DATE, listingOptions.getNumberOfDaysForNewListings() * -1) + "'";
			}

			String endTodayConition = "";
			if(sortBy != null && sortBy.equalsIgnoreCase("endtoday")) {
				endTodayConition = " AND endTime = '" + DateUtil.getTodaysDate() + "'";
			}

			String newTodayConition = "";
			if(sortBy != null && sortBy.equalsIgnoreCase("newtoday")) {
				newTodayConition = " AND startTime = '" + DateUtil.getTodaysDate() + "'";
			}

			StringBuffer sql = new StringBuffer();
			sql.append("SELECT itemId, title, quantity, shipPayment, startBid, endTime FROM items");
			sql.append(" WHERE ").append(titleCondition).append(typeCondition).append(langCondition).append(catCondition).append(locConition).append(timeConition).append(itemConition).append(priceFromConition).append(priceToConition).append(buyFromConition).append(buyToConition).append(endSoonConition).append(newListConition).append(endTodayConition).append(newTodayConition).append(";");

			System.out.println(sql.toString());
			populateBrowseItems(sql.toString());
		} else {
			execute();
			addActionError("The keyword you requested () is invalid or empty. Please enter some keywords to search for and try again.");
			return INPUT;
		}

		return SUCCESS;
	}

	public Integer getItemType() {
		return ItemType;
	}

	public void setItemType(Integer itemType) {
		ItemType = itemType;
	}

	public Integer getCategories() {
		return categories;
	}

	public void setCategories(Integer categories) {
		this.categories = categories;
	}

	public Integer getLocations() {
		return locations;
	}

	public void setLocations(Integer locations) {
		this.locations = locations;
	}

	public String getLanguages() {
		return languages;
	}

	public void setLanguages(String languages) {
		this.languages = languages;
	}

	public Itemtype getType() {
		return type;
	}

	public String[] getCategoriesList() {
		return categoriesList;
	}

	public List<BrowseItems> getItemList() {
		return itemList;
	}

	private void populateBrowseItems(String sql) {
		List tmpList = CommonFunctionDelegator.executeSQLQuery(sql.toString());

		for (Object object : tmpList) {
			Object[] objectArray = (Object[]) object;
			BrowseItems browseItems = new BrowseItems();
			browseItems.setItemId(Integer.parseInt(objectArray[0].toString()));
			browseItems.setTitle(objectArray[1].toString());
			browseItems.setQuantity((objectArray[2] != null) ? Integer.parseInt(objectArray[2].toString()) : 0);
			browseItems.setShipPayment((objectArray[3] != null) ? Double.parseDouble(objectArray[3].toString()) : 0);
			browseItems.setBuyPrice((objectArray[4] != null) ? Double.parseDouble(objectArray[4].toString()) : 0);
			try {
				browseItems.setEndTime(DateUtil.getDate(objectArray[5].toString(), "yyyy-MM-dd HH:mm:ss.S"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			this.itemList.add(browseItems);
		}
	}

	public String getTitleValue() {
		return titleValue;
	}

	public void setTitleValue(String titleValue) {
		this.titleValue = titleValue;
	}

	public Integer getSearchIn() {
		return searchIn;
	}

	public void setSearchIn(Integer searchIn) {
		this.searchIn = searchIn;
	}

	public Integer getQuantity() {
		return quantity;
	}

	public void setQuantity(Integer quantity) {
		this.quantity = quantity;
	}

	public Date getEndTime() {
		return endTime;
	}

	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}

	public Integer getBidderId() {
		return bidderId;
	}

	public void setBidderId(Integer bidderId) {
		this.bidderId = bidderId;
	}

	public Integer getSellerId() {
		return sellerId;
	}

	public void setSellerId(Integer sellerId) {
		this.sellerId = sellerId;
	}

	public Integer getItemId() {
		return itemId;
	}

	public void setItemId(Integer itemId) {
		this.itemId = itemId;
	}

	public Integer getBuyFrom() {
		return buyFrom;
	}

	public void setBuyFrom(Integer buyFrom) {
		this.buyFrom = buyFrom;
	}

	public Integer getBuyTo() {
		return buyTo;
	}

	public void setBuyTo(Integer buyTo) {
		this.buyTo = buyTo;
	}

	public Integer getPriceFrom() {
		return priceFrom;
	}

	public void setPriceFrom(Integer priceFrom) {
		this.priceFrom = priceFrom;
	}

	public Integer getPriceTo() {
		return priceTo;
	}

	public void setPriceTo(Integer priceTo) {
		this.priceTo = priceTo;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getSortBy() {
		return sortBy;
	}

	public void setSortBy(String sortBy) {
		this.sortBy = sortBy;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public Integer getPageSize() {
		return pageSize;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public boolean isTitleAndDescription() {
		return titleAndDescription;
	}

	public void setTitleAndDescription(boolean titleAndDescription) {
		this.titleAndDescription = titleAndDescription;
	}
}
